package com.fingard.dsp.bank.directbank.alipay01;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ICloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.CloseOrderState;
import com.fingard.dsp.bank.reqrespobj.closeorder.ReqCloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.RetAtsCloseOrder;

public class ALIPAY01CloseOrder extends ALIPAY01Base implements ICloseOrder {
	public RetAtsCloseOrder closeOrder(ReqCloseOrder p_req) {
		RetAtsCloseOrder retAts = new RetAtsCloseOrder(p_req.reqHeader);
		retAts.rdSeq = p_req.rdSeq;

		try {
			logIsExist();

			ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
			if (actItem != null) {
				String signType = "RSA";
				if ("CloseQROrder".equals(p_req.reqHeader.transType) || "CloseAPPOrder".equals(p_req.reqHeader.transType) || "CloseH5Order".equals(p_req.reqHeader.transType)) {
                    signType = "RSA2";
				}
                boolean useSignType = getBankConfig().getValueAsBool("useSignType");
                if (useSignType) {
                    signType = actItem.signType;
                }

				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);

				AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
				request.setBizContent("{\"out_trade_no\":\"" + p_req.rdSeq + "\"}");
				
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());

				AlipayTradeCloseResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());

				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if ("10000".equals(response.getCode())) {
					retAts.closeState = CloseOrderState.Close_Success;
				} else {
					String subCode = response.getSubCode();
					if ("ACQ.TRADE_NOT_EXIST".equals(subCode)) {
						retAts.closeState = CloseOrderState.Close_Success;
						retAts.respInfo = "Business Success";
					} else {
						retAts.closeState = CloseOrderState.Close_Fail;
						retAts.errorCode = response.getCode() + "+" + subCode;
						retAts.errorMsg = response.getSubMsg();
					}
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
